package com.feimt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feimt.common.CustomException;
import com.feimt.dto.SetmealDto;
import com.feimt.mapper.SetmealMapper;
import com.feimt.pojo.Setmeal;
import com.feimt.pojo.SetmealDish;
import com.feimt.service.SetmealDishService;
import com.feimt.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 宋孟林
 * @description
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    private SetmealDishService setmealDishService;

    @Autowired
    public SetmealServiceImpl(SetmealDishService setmealDishService) {
        this.setmealDishService = setmealDishService;
    }

    /**
     * 新增套餐自定义实现方法 操作对象是套餐dto
     * @param setmealDto 保存对象
     */
    @Transactional
    @Override
    public boolean saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        return setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 修改套餐时需要回显数据
     * @param id 回显的套餐id
     * @return 返回回显的套餐数据DTO
     */
    @Override
    public SetmealDto getData(Long id) {
        Setmeal setmeal = this.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id != null, SetmealDish::getSetmealId, id);
        if (setmeal != null){
            BeanUtils.copyProperties(setmeal, setmealDto);
            List<SetmealDish> list = setmealDishService.list(wrapper);
            setmealDto.setSetmealDishes(list);
            return setmealDto;
        }
        return null;
    }

    /**
     * 自定义删除套餐实现方法
     * @param ids 前端传递参数
     * @return 返回是否删除成功
     */
    @Transactional
    @Override
    public boolean deleteWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId, ids).eq(Setmeal::getStatus, 1);
        int count = this.count(wrapper);
        if (count > 0){
            throw new CustomException("套餐正在售卖，不能删除");
        }
        this.removeByIds(ids);
        LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(SetmealDish::getSetmealId, ids);
        return setmealDishService.remove(wrapper1);
    }
}
